<?php

namespace app\admin\controller\haipi;

use app\common\controller\Backend;
use app\common\model\Area;
use \app\common\model\haipi\Discuz as DiscuzModel;
use GuzzleHttp\Client;

/**
 * 论坛资源
 */
class Discuz extends Backend
{
    /**
     * Discuz模型对象
     * @var object
     * @phpstan-var \app\common\model\haipi\Discuz
     */
    protected object $model;

    protected array $noNeedLogin = ['fetchImage'];

    /**
     * 无需鉴权的方法
     * @var array
     */
    protected array $noNeedPermission = ['fetchImage'];

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id'];

    protected string|array $defaultSortField = 'weigh,desc';

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new DiscuzModel();
        $this->request->filter('clean_xss');
    }

    public function indexFilter($query){
        $search = $this->request->get('search/a');
        if($search){
            foreach($search  as  $value){
                if($value['field'] == 'areas_text'){
                        [$provinceCode, $cityCode, $dictrictCode] = Area::areaIdToCode($value['val']);
                        $query->where('city_code', $cityCode)
                        ->where('district_code', $dictrictCode)
                        ->where('province_code', $provinceCode);
                }
            }
        }
        $query->append(['areas_text', 'is_home']);
    }

    public function readFilter($model){
        $model->append(['areas']);
    }

    public function fetchImage(){
        $image = $this->request->get('image');
        if(!$image){
            $this->error('缺少参数');
        }
        $image = urldecode($image);
        $options = [
            'verify'          => false,
            'http_errors'     => false,
        ];
        $client = new Client($options);
        $response = $client->get($image, [
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1'
            ]
        ]);
        $body     = $response->getBody();
        $content  = $body->getContents();
        die($content);
    }
}